# 标签打印相关数据模型
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import json


class LabelTemplate(models.Model):
    """标签模板"""
    
    LABEL_SIZE_CHOICES = [
        ('8mm', '8mm'),
        ('12mm', '12mm'),
        ('18mm', '18mm'),
        ('24mm', '24mm'),
        ('36mm', '36mm'),
    ]
    
    PRINTER_MODEL_CHOICES = [
        ('pt-9500pc', 'Brother PT-9500PC'),
        ('generic', '通用打印机'),
    ]
    
    name = models.CharField('模板名称', max_length=100)
    description = models.TextField('模板描述', blank=True)
    
    # 标签规格
    label_size = models.CharField('标签尺寸', max_length=10, choices=LABEL_SIZE_CHOICES, default='24mm')
    printer_model = models.CharField('打印机型号', max_length=20, choices=PRINTER_MODEL_CHOICES, default='pt-9500pc')
    
    # 模板设计
    template_design = models.JSONField('模板设计', default=dict, help_text='包含字段布局、字体、样式等信息')
    
    # 字段配置
    fields_config = models.JSONField('字段配置', default=list, help_text='包含要打印的字段列表')
    
    # 打印设置
    print_settings = models.JSONField('打印设置', default=dict, help_text='打印机特定设置')
    
    # 预览图片
    preview_image = models.ImageField('预览图片', upload_to='label_previews/', blank=True)
    
    # 权限和共享
    is_public = models.BooleanField('公开模板', default=False)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建人')
    shared_users = models.ManyToManyField(User, related_name='shared_label_templates', blank=True)
    
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    is_active = models.BooleanField('是否启用', default=True)
    
    class Meta:
        verbose_name = '标签模板'
        verbose_name_plural = '标签模板'
        ordering = ['-updated_at']
    
    def __str__(self):
        return f"{self.name} ({self.label_size})"
    
    def get_label_width_px(self):
        """获取标签宽度像素值"""
        width_mapping = {
            '8mm': 64,
            '12mm': 96,
            '18mm': 144,
            '24mm': 192,
            '36mm': 288,
        }
        return width_mapping.get(self.label_size, 192)
    
    def get_available_fields(self):
        """获取可用字段列表"""
        from .models import Asset
        
        # 资产基础字段
        base_fields = [
            {'name': 'asset_number', 'label': '资产编号', 'type': 'text'},
            {'name': 'name', 'label': '资产名称', 'type': 'text'},
            {'name': 'category__name', 'label': '资产类别', 'type': 'text'},
            {'name': 'department__name', 'label': '所属部门', 'type': 'text'},
            {'name': 'location', 'label': '存放位置', 'type': 'text'},
            {'name': 'status', 'label': '资产状态', 'type': 'choice'},
            {'name': 'purchase_date', 'label': '采购日期', 'type': 'date'},
            {'name': 'purchase_price', 'label': '采购价格', 'type': 'decimal'},
            {'name': 'current_value', 'label': '当前价值', 'type': 'decimal'},
            {'name': 'manufacturer', 'label': '制造商', 'type': 'text'},
            {'name': 'model', 'label': '型号', 'type': 'text'},
            {'name': 'serial_number', 'label': '序列号', 'type': 'text'},
        ]
        
        # 自定义字段
        custom_fields = [
            {'name': 'qr_code', 'label': '二维码', 'type': 'qrcode'},
            {'name': 'barcode', 'label': '条形码', 'type': 'barcode'},
            {'name': 'current_date', 'label': '当前日期', 'type': 'date'},
            {'name': 'print_date', 'label': '打印日期', 'type': 'date'},
            {'name': 'custom_text', 'label': '自定义文本', 'type': 'text'},
        ]
        
        return base_fields + custom_fields


class LabelPrintJob(models.Model):
    """标签打印任务"""
    
    STATUS_CHOICES = [
        ('pending', '等待打印'),
        ('printing', '打印中'),
        ('completed', '打印完成'),
        ('failed', '打印失败'),
        ('cancelled', '已取消'),
    ]
    
    template = models.ForeignKey(LabelTemplate, on_delete=models.CASCADE, verbose_name='标签模板')
    
    # 打印对象
    asset_ids = models.JSONField('资产ID列表', default=list)
    
    # 打印设置
    copies = models.IntegerField('打印份数', default=1)
    print_settings = models.JSONField('打印设置', default=dict)
    
    # 任务状态
    status = models.CharField('打印状态', max_length=20, choices=STATUS_CHOICES, default='pending')
    
    # 执行信息
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建人')
    started_at = models.DateTimeField('开始时间', null=True, blank=True)
    completed_at = models.DateTimeField('完成时间', null=True, blank=True)
    
    # 结果信息
    total_labels = models.IntegerField('总标签数', default=0)
    printed_labels = models.IntegerField('已打印数', default=0)
    failed_labels = models.IntegerField('失败数', default=0)
    error_message = models.TextField('错误信息', blank=True)
    
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    
    class Meta:
        verbose_name = '标签打印任务'
        verbose_name_plural = '标签打印任务'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"打印任务 {self.id} - {self.template.name}"
    
    @property
    def success_rate(self):
        """成功率"""
        if self.total_labels == 0:
            return 0
        return (self.printed_labels / self.total_labels) * 100


class PrinterConfiguration(models.Model):
    """打印机配置"""
    
    CONNECTION_TYPE_CHOICES = [
        ('usb', 'USB连接'),
        ('network', '网络连接'),
        ('bluetooth', '蓝牙连接'),
    ]
    
    name = models.CharField('配置名称', max_length=100)
    printer_model = models.CharField('打印机型号', max_length=50, default='pt-9500pc')
    
    # 连接配置
    connection_type = models.CharField('连接类型', max_length=20, choices=CONNECTION_TYPE_CHOICES, default='usb')
    connection_params = models.JSONField('连接参数', default=dict)
    
    # 打印机设置
    default_settings = models.JSONField('默认设置', default=dict)
    
    # 状态
    is_active = models.BooleanField('是否启用', default=True)
    is_default = models.BooleanField('默认配置', default=False)
    
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建人')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        verbose_name = '打印机配置'
        verbose_name_plural = '打印机配置'
    
    def __str__(self):
        return f"{self.name} ({self.printer_model})"
    
    def save(self, *args, **kwargs):
        # 确保只有一个默认配置
        if self.is_default:
            PrinterConfiguration.objects.filter(is_default=True).update(is_default=False)
        super().save(*args, **kwargs)


class LabelPrintHistory(models.Model):
    """标签打印历史"""
    
    print_job = models.ForeignKey(LabelPrintJob, on_delete=models.CASCADE, verbose_name='打印任务', null=True, blank=True)
    asset = models.ForeignKey('Asset', on_delete=models.CASCADE, verbose_name='资产', null=True, blank=True)
    
    # 打印信息
    label_data = models.JSONField('标签数据', default=dict)
    print_command = models.TextField('打印命令', blank=True)
    
    # 结果
    is_successful = models.BooleanField('是否成功', default=False)
    error_message = models.TextField('错误信息', blank=True)
    
    printed_at = models.DateTimeField('打印时间', auto_now_add=True)
    
    class Meta:
        verbose_name = '标签打印历史'
        verbose_name_plural = '标签打印历史'
        ordering = ['-printed_at']
    
    def __str__(self):
        return f"{self.asset.asset_number} - {self.printed_at.strftime('%Y-%m-%d %H:%M')}"